'use strict';
module.exports = (options, app) => {
  return async function blogauth(ctx, next) {
    await next();
    const new_ip = ctx.request.ip;
    if (new_ip === '120.27.20.14') return false;
    const date = Date.parse(new Date()) / 1000;
    const session_blog = ctx.session.SESSION_BLOG;
    const visitor = await app.mysql.get('visit', { session: session_blog });
    if (!session_blog || !visitor) {
      const visit_session = 'blog_' + date;
      ctx.session.SESSION_BLOG = visit_session;
      app.mysql.insert('visit', { session: visit_session, ip: new_ip, visit_time: date, visit_last_time: date });
    } else {
      let { ip, times, id, visit_last_time } = visitor;
      if ((visit_last_time - date) < (60 * 2)) return false;
      if (ip.indexOf(new_ip) === -1) ip += (',' + new_ip);
      app.mysql.update('visit', { id, ip, times: times += 1, visit_last_time: date });
    }
  };
};
